package cn.kailangtu.dataspot.activify;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.navigation.fragment.NavHostFragment;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import cn.kailangtu.commonevents.eventEntity.DataBeanChangedEvent;
import cn.kailangtu.commonevents.eventEntity.FragmentChangedEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardConfirmCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardConfirmOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardConfirmResultEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardLockerResultEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardTimeOpenEvent;
import cn.kailangtu.commonevents.eventEntity.LocalSettingChangedEvent;
import cn.kailangtu.commonevents.eventEntity.OnFragmentChangeEvent;
import cn.kailangtu.commonevents.eventEntity.OpenContactEvent;
import cn.kailangtu.commonevents.eventEntity.OpenPrincipleEvent;
import cn.kailangtu.commontools.APPSPUtils;
import cn.kailangtu.commontools.AppVariable;
import cn.kailangtu.commontools.KeyboardUtils;
import cn.kailangtu.commontools.ToastUtils;
import cn.kailangtu.dataspot.R;
import cn.kailangtu.dataspot.data.ControlTree;
import cn.kailangtu.dataspot.data.ControlTreeNode;
import cn.kailangtu.dataspot.data.HighData;
import cn.kailangtu.dataspot.data.PageIndex;
import cn.kailangtu.dataspot.data.consts.ControlAction;
import cn.kailangtu.dataspot.data.context.SelectContext;
import cn.kailangtu.dataspot.databinding.FragmentFactorySettingBinding;
import cn.kailangtu.dataspot.db.ExceptionLogEntity;
import cn.kailangtu.dataspot.db.OptionLogEntity;
import cn.kailangtu.dataspot.db.SwitchLogEntity;
import cn.kailangtu.dataspot.status;
import cn.kailangtu.dataspot.tasks.BaseTask;

public class FactorySettingFragment extends BaseFragment {

    private FragmentFactorySettingBinding binding;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFactorySettingBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListen();
        EventBus.getDefault().post(new FragmentChangedEvent(R.layout.fragment_factory_setting));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    @Override
    protected void resetPageIndex() {
        status.localPageIndex = PageIndex.H_FACTORY_SET;
        if (status.localToPlc != 2) {
            BaseTask.toNewPage(status.localPageIndex);
        }
    }

    @Override
    void resetPlatform() {
        if(AppVariable.platform_version == 450 && AppVariable.need_reset_view) {
            commonReset(binding.rlFactorySettingContainer, -20, 0, 0, 20);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OnFragmentChangeEvent event) {
        // Do something
        if(R.layout.fragment_factory_setting == event.getTargetFragmentId())
        {

        }
        else if(R.layout.fragment_switch_test == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(FactorySettingFragment.this)
                    .navigate(R.id.action_FactorySettingFragment_to_SwitchTestFragment);
        }
        else if(R.layout.fragment_common_setting == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(FactorySettingFragment.this)
                    .navigate(R.id.action_FactorySettingFragment_to_CommonSettingFragment);
        }
        else if(R.layout.fragment_exception_log == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(FactorySettingFragment.this)
                    .navigate(R.id.action_FactorySettingFragment_to_ExceptionLogFragment);
        }
        else if(R.layout.fragment_real_picture == event.getTargetFragmentId())
        {
            NavHostFragment.findNavController(FactorySettingFragment.this)
                    .navigate(R.id.action_FactorySettingFragment_to_RealPictureFragment);
        }
    }

    private void initListen(){

        binding.tvFactorySettingTitle41.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.currentLockerTargetSourceId = binding.tvFactorySettingTitle41.getId();
                EventBus.getDefault().post(new KeyboardLockerOpenEvent());
            }
        });
        binding.tvFactorySettingTitle42.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.currentLockerTargetSourceId = binding.tvFactorySettingTitle42.getId();
                EventBus.getDefault().post(new KeyboardLockerOpenEvent());
            }
        });
        binding.tvFactorySettingTitle44.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.currentConfirmSourceId = binding.tvFactorySettingTitle44.getId();
                EventBus.getDefault().post(new KeyboardConfirmOpenEvent("确定删除故障记录？"));
            }
        });
        binding.tvFactorySettingTitle45.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.currentConfirmSourceId = binding.tvFactorySettingTitle45.getId();
                EventBus.getDefault().post(new KeyboardConfirmOpenEvent("确定删除运行记录？"));
            }
        });

        binding.tvFactorySettingTitle46.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status.currentConfirmSourceId = binding.tvFactorySettingTitle46.getId();
                EventBus.getDefault().post(new KeyboardConfirmOpenEvent("确定删除运行记录？"));
            }
        });

        binding.tvFactorySettingTitle43.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new KeyboardTimeOpenEvent());
            }
        });

        binding.tvFactorySettingTitle61.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new OpenPrincipleEvent());
            }
        });
        binding.tvFactorySettingTitle62.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new OpenContactEvent());
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardConfirmResultEvent event){
        if(event.isToDo())
        {
            if(status.currentConfirmSourceId == binding.tvFactorySettingTitle44.getId()) {
                LitePal.deleteAll(ExceptionLogEntity.class);
            }
            else if(status.currentConfirmSourceId == binding.tvFactorySettingTitle45.getId()) {
                LitePal.deleteAll(OptionLogEntity.class);
            }
            else if(status.currentConfirmSourceId == binding.tvFactorySettingTitle46.getId()) {
                LitePal.deleteAll(SwitchLogEntity.class);
            }
        }
        status.currentConfirmSourceId = 0;
        EventBus.getDefault().post(new KeyboardConfirmCloseEvent());
    }



    private void processTreeNode(ControlTreeNode node)
    {

        if(node.getChildren() != null)
        {
            for(int i = 0;i< node.getChildren().size();i++)
            {
                processTreeNode(node.getChildren().get(i));
            }
        }
        if(node.getAddress() > 0)
        {
            TextView textView =  this.getActivity().findViewById(node.getTargetControlId());
            KeyboardUtils.setNewValue(textView, String.valueOf(HighData.getInstance().getValue(node.getAddress())),node.getSelection(),node.getProcessType());
        }
    }



    @Override
    protected int processControlsEvent(int eventType) {
        if(eventType == ControlAction.Selection)
        {
           TextView textView =  this.getActivity().findViewById(controlTree.getSelectNode().getIndex());
           SelectContext.setSelectedView(textView);
           if(controlTree.getSelectNode().getIndex() == binding.tvFactorySettingTitle5.getId()){
               binding.svContainer.smoothScrollTo(0,1000);
           }
           else if(controlTree.getSelectNode().getIndex() == binding.tvFactorySettingTitle1.getId()
                || controlTree.getSelectNode().getIndex() == binding.tvFactorySettingTitle2.getId()
           ){
               binding.svContainer.smoothScrollTo(0,0);
           }
           else if(controlTree.getSelectNode().getIndex() == binding.tvFactorySettingTitle3.getId()
               || controlTree.getSelectNode().getIndex() == binding.tvFactorySettingTitle4.getId())
           {
               binding.svContainer.smoothScrollTo(0,450);
           }

        }
        else if(eventType == ControlAction.Entry){
            openKeybaord();
        }
        return 0;
    }

    @Override
    protected void buildControlTree() {
        controlTree = ControlTree.getFactorySetting();
        controlTree.setSelectNode(null);
        resetData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DataBeanChangedEvent event){

        resetData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LocalSettingChangedEvent event){
        resetLocalData();
    }

    private void resetData()
    {
        int currentValue11 = (HighData.getInstance().getValue(3506) + HighData.getInstance().getValue(3506) +HighData.getInstance().getValue(3506)) /3;
        binding.tvFactorySettingValueTwo11.setText(currentValue11+"V");

        binding.tvFactorySettingValueTwo11.setText(HighData.getInstance().getValue(3505)+"V");

        binding.tvFactorySettingValueTwo12.setText(HighData.getInstance().getValue(3509)+"A");
        binding.tvFactorySettingValueTwo13.setText(HighData.getInstance().getValue(3510)+"A");
        binding.tvFactorySettingValueTwo14.setText(HighData.getInstance().getValue(3511)+"A");
        binding.tvFactorySettingValueTwo15.setText(HighData.getInstance().getValue(3512)+"");



        processTreeNode(controlTree.getRootNode());
        resetLocalData();
    }

    private void resetLocalData()
    {
        binding.tvFactorySettingValue21.setText(""+APPSPUtils.getInstance().getLocalIpEth0());
        binding.tvFactorySettingValue22.setText(""+APPSPUtils.getInstance().getLocalMaskEth0());
        binding.tvFactorySettingValue23.setText(""+APPSPUtils.getInstance().getLocalIpEth1());
        binding.tvFactorySettingValue24.setText(""+APPSPUtils.getInstance().getLocalMaskEth1());
        binding.tvFactorySettingValue25.setText(""+APPSPUtils.getInstance().getCameraIp());
        binding.tvFactorySettingValue26.setText(""+APPSPUtils.getInstance().get红外测温视频Switch());


        binding.tvFactorySettingValue31.setText(""+APPSPUtils.getInstance().getSerialPort1());
        binding.tvFactorySettingValue32.setText(""+APPSPUtils.getInstance().getSerialBaudPort1());
        binding.tvFactorySettingValue33.setText(""+APPSPUtils.getInstance().getSerialCheckPort1());
        binding.tvFactorySettingValue34.setText(""+APPSPUtils.getInstance().getSerialPort2());
        binding.tvFactorySettingValue35.setText(""+APPSPUtils.getInstance().getSerialBaudPort2());
        binding.tvFactorySettingValue36.setText(""+APPSPUtils.getInstance().getSerialCheckPort2());
        binding.tvFactorySettingValue37.setText(""+APPSPUtils.getInstance().getChatRefreshTime()+"s");


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardLockerResultEvent event)
    {
        if(event.isSave())
        {
            if(status.currentLockerTargetSourceId == binding.tvFactorySettingTitle41.getId())
            {
                APPSPUtils.getInstance().putCommonSettingPwd(event.getNewPwd());
            }
            else if(status.currentLockerTargetSourceId == binding.tvFactorySettingTitle42.getId())
            {
                APPSPUtils.getInstance().putFactorySettingPwd(event.getNewPwd());

            }
            ToastUtils.ShowInCenter(getContext(),"操作完成");

        }

        EventBus.getDefault().post(new KeyboardLockerCloseEvent());
    }



}